<template>
    <div class="searchCon">
        <div :class="scrollClass?'searchTop_fixed':'searchTop'"  id="searchTop">
            <!-- 取消按钮-->
            <div class="close_search" @click="hide_page">
                取消
            </div>
            <!--搜索框-->
            <form action="#" @submit.prevent="searchEvent" @click="show_page">
                <i class="iconfont icon-sou searchIcon" ref="icon" @click="searchEvent"></i>
                <input type="text" ref="searchBox" class="search_ipt" @keyup='search' :placeholder="fontContent" v-model.trim="searchKey" @focus="focuss" @blur="blurr" maxlength="15">
                <img src="../../images/newClose.png" alt="">
            </form>

            <!--<div class="s_inputCon">-->
            <!--<div class="selectCon" @click="show = !show">-->
            <!--<div class="selectSite">-->
            <!--<p>{{checked}}</p>-->
            <!--<transition enter-active-class="bounceDown" leave-active-class="bounce" v-if="show && types.length>1">-->
            <!--&lt;!&ndash; 选择类型&ndash;&gt;-->
            <!--<ul>-->
            <!--<li @click.stop="selectType(item.key)" v-for="(item, index) in types" :key="index">-->
            <!--{{item.name}}-->
            <!--</li>-->
            <!--</ul>-->
            <!--</transition>-->
            <!--</div>-->
            <!--</div>-->
            <!--&lt;!&ndash; 输入框&ndash;&gt;-->
            <!--<form action="#" class="searchInput" @submit.prevent="searchEvent" @click="show_page">-->
            <!--<input type="text" class="searchInput2" v-model.trim="searchKey" :placeholder="fontConent" @focus="focuss"-->
            <!--@blur="blurr" ref='searchBox' v-if="type === 'mecth'" maxlength="15">-->
            <!--<input type="text" class="searchInput2" v-model.trim="searchKey" :placeholder="fontConent" @focus="focuss"-->
            <!--@blur="blurr" ref='searchBox' v-else="type === 'coupon'" maxlength="15">-->
            <!--</form>-->
            <!--&lt;!&ndash; 搜索按钮&ndash;&gt;-->
            <!--<span class="searchBtnCon" @click="searchEvent"><i class="icon iconfont icon-sou searchBtn"></i></span>-->
            <!--</div>-->
        </div>

        <div class="searchPage" v-if="searchPage" id="searchCon">
            <!-- 发现栏 -->
            <div class="findCon">
                <div class="search_tit2">
                    <span class="event_btn" @click="getNewTag"><img src="../../images/shuaxin.png" alt="">换一组</span>
                    <span class="find">你可能在找</span>
                </div>
                <div class="find_list" v-if="tagList.length !=0">
                    <ul class="clearfix">
                        <li v-for="item in tagList" @click="searchTag(item.des)" class="white_bg">{{item.des}}</li>
                    </ul>
                </div>
            </div>
            <!--搜索历史 -->
            <div class="historyCon" v-if="historyTab">
                <div class="search_tit">
                    <span class="event_btn" @click="clearHistory"><img src="../../images/dele.png" alt="">清除</span>
                    <span class="find">历史记录</span>
                </div>
                <ul class="history_list">
                    <!-- 电子券 -->
                    <li v-for="(item, index) in historyList" @click="searchHistory(item)"
                        v-if="searchType === 'coupon' && item.type == 'coupon' && item.info!=''" :key="index" class="white_bg">
          <span class="list_icon">
            <icon iconName="#icon-lishidianziquan-"></icon>
          </span>
                        <a href="javascript:;">{{item && item.info}}</a>
                    </li>
                    <!-- 商户 -->
                    <li v-for="(item, index) in historyList" @click="searchHistory(item)"
                        v-if="searchType === 'mecth' && item.type == 'mecth' && item.info!=''" :key="index" class="white_bg">
          <span class="list_icon">
            <!--<icon iconName="#icon-lishishanghu-" otherClass="list_icon"></icon>-->
          </span>
                        <a href="javascript:;">{{item && item.info}}</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>
<script>
    import {mapState} from 'vuex'
    import {Toast, Indicator} from 'mint-ui'
    import getData from '../../service/getData.js'
    import * as types from '../../vuex/types.js'
    import SearchBarView from 'src/componentes/global/search_bar.vue'
    import {Storage} from 'src/utils/storage.js'

    export default {
        name: "newSearch-bar",
        components: {SearchBarView},
        data() {
            return {
                fontContent: "输入商户名、商家、商圈、分类",
                fontConent: "请输入商户名称",
                show: false,
                leftBar: false,
                searchPage: false,
                showPage: '',
                types: [
                    {key: 'mecth', name: '商户'},
                    {key: 'coupon', name: '电子券'}
                ],
                type: '',
                tagList: [],
                searchKey: '',
                historyTab: false,
                isChooCity: false,
                scrollClass: false,
            }
        },
        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo, //用户信息
                historyList: state => state.coupon.historyList, // 搜索关键字
                searchType: state => state.coupon.searchType, // 搜索类型
                keyWord: state => state.coupon.searchKey // 搜索类型
            }),
            checked() {
                let val;
                if (this.showCity) {
                    val = this.checkedCity
                } else {
                    let types = this.types.find(item => item.key === this.searchType); // 根据搜索类型取得搜索项
                    this.types = types; // 赋值搜索项，mecth和coupon只会留对象选项下来，不准点击下拉选择
                    val = types.name // 显示搜索类名
                }
                return val
            }
        },
        props: {
            'checkedCity': {
                type: String,
                default: ''
            },
            'showCity': {
                type: Boolean,
                default: false
            }
        },
        created: function () {
            window.addEventListener('scroll', this.handleScroll);
            //解决ios返回出现空白问题
            setTimeout(function () {
                window.scrollTo(0, 1);
                window.scrollTo(0, 0);
            }, 100);
            this.historyTab = !!Storage.get("history_info");
            var randomNum;
            if (!Storage.get("tag", true) || Storage.get("tag", true).length == 0) {
                getData.tagList().then(rep => {
                    if (rep.content.length != 0) {
                        Storage.set("tag", rep.content, true);
                        randomNum = rep.content.length >= 8 ? 8 : rep.content.length
                        this.tagList = this.randomArray(rep.content, randomNum);
                    }
                })
            } else {
                randomNum = Storage.get("tag", true).length >= 8 ? 8 : Storage.get("tag", true).length
                this.tagList = this.randomArray(Storage.get("tag", true), randomNum);
            }
        },
        mounted() {
            let router = this.$route.query
            if (router.type === 'home') {
                this.searchPage = true
            }
            //加载缓存是搜索商户还是电子券
            if (this.searchType) {
                this.searchKey = '';
                this.$store.commit("search_type", this.searchType);
                if (this.searchType === 'coupon') {
                    this.fontConent = "请输入电子券名称";
                } else {
                    this.fontConent = "请输入商户名称";
                }
            }
        },
        methods: {
            handleScroll() {
                var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                if (scrollTop >= 40) {
                    this.scrollClass = true;
                } else {
                    this.scrollClass = false;
                }
            },
            selectType: function (type) {
                this.searchKey = '';
                this.$nextTick(() => {
                    this.show = false
                });
                this.type = type
                this.blurr()
                this.$store.commit("search_type", type);
                this.$store.commit("search_key", this.searchKey);
                this.show_page();
            },
            focuss: function () {
                this.fontConent = "";
                this.show = false
            },
            blurr: function () {
                if (this.searchType === 'coupon') {
                    this.fontConent = "请输入电子券名称";
                } else {
                    this.fontConent = "请输入商户名称";
                }
            },
            show_page: function () {
                this.searchKey = "";
                this.searchPage = true;
                // this.show = false;
                if (Storage.get("history_info")) {
                    this.historyTab = true;
                } else {
                    this.historyTab = false;
                }
                this.$emit('hidden-view', false);
            },
            hide_page() {
                let router = this.$route.query
                if (router.type === 'home') {
                    this.$router.back()
                } else {
                    this.searchKey = ''
                    this.$store.commit("search_key", this.searchKey);
                    this.searchEvent();
                    this.show = false
                    this.searchPage = false
                    this.$emit('hidden-view', true)
                }
            },
            searchHistory: function (item) { //点击搜索历史
                this.searchKey = item.info;
                this.$store.commit("search_key", item.info);
                this.$store.commit("search_type", item.type);
                this.searchEvent();
            },
            searchTag: function (key) { //点击标签
                this.searchKey = key;
                this.$store.commit("search_key", key);
                this.searchEvent();
            },
            searchEvent: function () {
                if (!this.searchKey) {
//    	return
                }
                this.$store.commit(types.GET_PAGE_NUM, 1)
                this.$store.commit("search_key", this.searchKey);
                this.$store.commit("search_type", this.searchType); //设置搜索类型//cop、mer
                this.addSearchInfo(); //添加搜索历史
                let router = this.$route.query
                if (router.type === 'home') {
                    Storage.set("menuArr", Storage.get('menu', true), true);
                    this.$store.commit(types.coupon_tit, '全部')
                    this.$router.push({
                        name: 'couponSearch',
                        query: {type: true}
                    })
                } else {
                    this.searchPage = false
                    this.$store.commit(types.coupon_tit, '全部')
                    this.$emit('click-search')
                }
            },
            clearHistory: function () {

                //    Storage.remove("history_info");
                //    this.$store.commit("history_info", []); //设置搜索历史
                var newArray = Storage.get("history_info");
                var shuziArray = [];
                var i;
                newArray.find(function (item, index) {
                    if (item.type == "coupon") {
                        shuziArray.push(index);
                        i = shuziArray.length
                    }
                });

                if (this.searchType == "coupon") {
                    newArray.splice(0, i);
                    Storage.set("history_info", newArray); //保存至本地
                    this.$store.commit("history_info", newArray); //设置搜索历史
                } else {
                    newArray.splice(-(newArray.length - i));
                    Storage.set("history_info", newArray); //保存至本地
                    this.$store.commit("history_info", newArray); //设置搜索历史
                }


                Toast({
                    message: '操作成功',
                    duration: 1000
                });
                this.historyTab = false;
            },
            addSearchInfo: function () {
                let array = Storage.get("history_info") || [];
                let merchArr = [];
                let couponArr = [];
                array.forEach(item => {
                    if (item.type === 'mecth') {
                        merchArr.push(item)
                    } else if (item.type === 'coupon') {
                        couponArr.push(item)
                    }
                });
                // 判断是否重复
                let val = array.find(item => item.info === this.searchKey && item.type === this.searchType);
                if (this.searchType == 'coupon') {
                    couponArr.unshift({
                        type: 'coupon',
                        info: this.searchKey
                    });
                    if (couponArr.lastIndexOf(val) > 0) { //查找相同元素   放在第一位
                        couponArr.splice(couponArr.lastIndexOf(val), 1)
                    }
                    couponArr = couponArr.slice(0, 10)
                } else {
                    merchArr.unshift({
                        type: 'mecth',
                        info: this.searchKey
                    });
                    if (merchArr.lastIndexOf(val) > 0) { //查找相同元素   放在第一位
                        merchArr.splice(merchArr.lastIndexOf(val), 1)
                    }
                    merchArr = merchArr.slice(0, 10)
                }
                array = couponArr.concat(merchArr);
                Storage.set("history_info", array); //保存至本地
                this.$store.commit("history_info", array); //设置搜索历史
            },
            randomArray: function (arr, count) {
                var shuffled = arr.slice(0),
                    i = arr.length,
                    min = i - count,
                    temp, index;
                while (i-- > min) {
                    index = Math.floor((i + 1) * Math.random());
                    temp = shuffled[index];
                    shuffled[index] = shuffled[i];
                    shuffled[i] = temp;
                }
                return shuffled.slice(min);
            },
            getNewTag: function () {
                if (Storage.get("tag", true).length < 8) {
                    return;
                }
                this.tagList = this.randomArray(Storage.get("tag", true), 8);
            }
        },
        beforeRouteLeave(to, from, next) {
            window.removeEventListener('scroll', this.handleScroll);

            next()
        }
    }
</script>

<style scoped>
    .fun_icon i {
        font-size: 1.2rem;
    }

    .location {
        font-size: 1rem;
    }

    .city ul {
        position: absolute;
        overflow: hidden;
        left: 0;
        top: 2.5rem;
        background: #eb4f89;
        width: 5rem;
        z-index: 5;
        border-bottom-left-radius: .2rem;
        border-bottom-right-radius: .2rem;
    }

    .searchCon {
        position: relative;
        height: 4.334rem;
        width: 100%;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        z-index: 111;
        -webkit-overflow-scrolling: touch;
    }

    .searchTop {
        position: static;
        left: 0;
        right: 0;
        top: 0;
        height: 4.5rem;
        padding: .667rem 0;
        z-index: 12;
    }

    .searchTop_fixed {
        left: 0;
        right: 0;
        top: 0;
        height: 3rem;
        padding: .667rem 0;
        z-index: 12;
        position: fixed;
        top: 0;
        left: 0;
    }

    /*整左侧*/

    .s_inputCon {
        height: 3rem;
        line-height: 3rem;
        position: absolute;
        z-index: 3;
        margin: 0 0 0 .667rem;
        width: -webkit-calc(100% - 5.1rem);
        /*display: flex;*/
    }

    .city {
        width: 5rem;
        height: 100%;
        background: #eb4f89;
        border-top-left-radius: .2rem;
        border-bottom-left-radius: .2rem;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 2;
        text-align: center;
        color: #fff;
        font-size: 1rem;
    }

    .selectCon {
        width: 23%;
        height: 100%;
        background: #eb4f89;
        border-top-left-radius: .2rem;
        border-bottom-left-radius: .2rem;
        float: left;
        position: relative;
    }

    .selectSite {
        padding: 0 .4rem;
        /*color:#f0cbd7;*/
        color: #fff;
        position: relative;
        float: left;
    }

    .selectCon ul {
        position: absolute;
        overflow: hidden;
        left: 0;
        top: 2.5rem;
        background: #eb4f89;
        width: 5rem;
        z-index: 5;
        border-bottom-left-radius: .2rem;
        border-bottom-right-radius: .2rem;
    }

    .selectCon ul li {
        padding-left: .4rem;
    }

    .downIcon {
        color: #f0cbd7;
        margin-left: 0;
        font-size: 1rem;
        position: absolute;
        right: 0;
        top: 0;
        z-index: 1;
    }

    .searchInput {
        height: 100%;
        float: left;
        /*flex: 1;*/
        width: 62%;
        color: #fff;
        background: -webkit-linear-gradient(to right, #eb4f89, #f85b7b);
        background: linear-gradient(to right, #eb4f89, #f85b7b);
        border-radius: 0;
    }

    .searchInput2 {
        width: 100%;
        height: 100%;
        text-indent: .4rem;
        font-size: 1rem;
        background: transparent;
        color: #fff;
    }

    .searchInput2::-webkit-input-placeholder {
        color: #fff;
    }

    .searchBtnCon {
        height: 3rem;
        width: 14%;
        line-height: 3.2rem;
        background: #f85b7b;
        float: left;
        border-top-right-radius: .2rem;
        border-bottom-right-radius: .2rem;
        text-align: center;
    }

    .searchBtn {
        color: #fff;
        font-size: 2rem;
    }

    .search_right_box {
        overflow: hidden;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        border-radius: .2rem;
    }
    .searchPage {
        position: relative;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background: #F5F5F5;
    }

    .findCon {
        overflow: hidden;
        margin-top: 0;
    }
    .find_list{
        padding:0 .08rem;
    }
    .find_list li {
        float: left;
        width: -webkit-calc((100% - 3.335rem) / 4);
        height: 2.2rem;
        line-height: 2.4rem;
        /*background: #fff;*/
        margin-left: .667rem;
        font-size:.85rem;
        color:rgb(68,68,68);
        -webkit-border-radius:3px;
        -moz-border-radius:3px;
        border-radius:3px;
        margin-bottom: .667rem;
        text-align: center;
    }

    .search_tit {
        color: #999;
        padding:.3rem .8rem;
        /*background: #fff;*/
        height:2.8rem;
        line-height:2.8rem;
    }

    .search_tit2 {
        padding: 0 .8rem;
        height: 3rem;
        line-height: 3rem;
    }

    .historyCon {
        overflow: hidden;
    }

    .event_btn {
        float: right;
        font-size:1rem;
        color:rgb(153,153,153);
    }
    .history_list {
        overflow: hidden;
        padding:0 0.08rem;
    }

    .history_list li {
        float: left;
        margin: .667rem 0 0 .667rem;
        line-height: 2.4rem;
        padding: 0 .4rem;
        text-align: center;
    }

    .history_list span.list_icon {
        float: left;
        font-size: 1.6rem;
        margin-right: .4rem;
    }

    .history_list a {
        color: #969696;
        font-size:.85rem;
    }

    .close_search {
        width: 3rem;
        height: 3rem;
        line-height:3.8rem;
        position: absolute;
        z-index: 5;
        right: .667rem;
        color:rgb(239,75,138);
        font-size:1rem;
        font-weight:400;
        text-align: center;
    }
    /*改版的搜索框样式*/
    /*<!--搜索-->*/
    form {
        padding:.8rem 0 0 .8rem;
    }

    .searchIcon {
        position: absolute;
        top:2.1rem;
        left:1.4rem;
        z-index: 100;
        font-size:1.15rem;
    }

    .search_ipt {
        width:82%;
        height: 2.3rem;
        position: relative;
        border-radius:100px;
        background-color:rgb(255,255,255);
        text-indent:2rem;
        box-shadow: -4px 0px 4px #f0f0f0,
        0px -4px 4px #f0f0f0,
        4px 0px 4px #f0f0f0,
        0px 4px 4px #f0f0f0;
    }

    .search_ipt::-webkit-input-placeholder {
        padding-left:.3rem;
        font-size:1rem;
        color:rgb(153,153,153);
    }
    form img{
        width:1rem;
        height:1rem;
        position:absolute;
        top:2.15rem;
        right:5rem;
    }
    .event_btn img{
        width:1rem;
        height:1.15rem;
        vertical-align: -2px;
        padding-right: .5rem;
    }
    .historyCon{
        margin-top:1.5rem;
        border-top:1px solid rgb(237,237,237);
    }
    .find{
        font-size:1rem;
        color:rgb(102,102,102);
    }
</style>
